<!--
 * @Date: 2020-07-11 16:42:56
 * @LastEditors: leehave
 * @LastEditTime: 2020-09-09 13:12:16
-->
<template>
  <div class="balance-wrapper">
    <div class="card-container" v-if="deviceInfo.device">
      <div class="card-content">
        <div class="balance">
          账户余额：
          <span>{{walletAccount}}元</span>
        </div>
        <div class="services-site">服务站点：{{deviceInfo.device.area}}</div>
      </div>
    </div>
    <van-cell>
      <div slot="title">
        <div class="van-cell-text">充值选项</div>
      </div>
      <div class="choose-option">
        <van-radio-group
          v-model="balanceOption"
          @change="selectBalance"
          class="option-radio--group"
        >
          <van-radio name="1">钱包</van-radio>
          <van-radio name="2">离线电卡充值</van-radio>
        </van-radio-group>
      </div>
    </van-cell>

    <van-cell-group class="ecard-input" v-if="balanceOption == 2">
      <van-field
        v-model="ecardNum"
        center
        clearable
        label
        placeholder="请输入充值卡号"
        :border="false"
      />
      <van-field
        v-model="ecardNumComp"
        center
        clearable
        label
        placeholder="请再次输入充值卡号"
        :border="false"
      />
    </van-cell-group>

    <div class="select-money--button">
      <div class="top-up--options">
        <div
          class="select-option"
          :class="item.active ? 'active' : ''"
          v-for="(item,index) in optionList"
          :key="item.id"
          @click="onTap(item,index)"
        >
          <div class="select-block">
            <div class="num">{{item.chargeAmount}}元</div>
            <div class="discounts">赠送{{item.givingAmount}}元</div>
          </div>
        </div>
      </div>
    </div>

    <van-button round color="#409EFF" block @click="handlePay">确认支付</van-button>

    <notice-panel
      type="warning"
      title="温馨提示"
      desc="未消费完的余额可退费（扣除赠送金额），您充值的金额直接进入您所属运营商的微信账户，点击充值表示您已知晓，并阅读和认可犀牛共享充电平台“免责声明”内容！"
    ></notice-panel>
  </div>
</template>

<script>
import {
  queryDeviceActive,
  openPayment,
  getBindCardInfo,
  queryByQrCode,
} from "@/service/user";
import balanceCard from "@/components/balance-card/index";
import noticePanel from "@/components/notice-panel/index";
import { mapGetters } from "vuex";
export default {
  data() {
    return {
      balanceOption: "1",
      ecardNum: "",
      ecardNumComp: "",
      protocolCheck: false,
      optionList: [],
      chargeType: "wallet", //balanceOption => 1 钱包 2 => 离线卡 3 => wechat
      qrNum: "",
      money: "", //选择的金额(元)
      nominalValue: "", // 活动充值金额（元）/次
      coupon: "", // 活动赠送金额（元）/次
      cardInfoList: "", //用户卡信息
      deviceInfo: {}, //设备信息
    };
  },
  computed: {
    ...mapGetters(["userInfo"]),
    walletAccount(){
      return this.userInfo.points + this.userInfo.givePoints
    }
  },
  created() {
    let routerQuery = this.$route.query;
    console.log(routerQuery,'routerQuery')
    if(this.userInfo && this.userInfo.openId !== undefined){

      if (
        routerQuery.hasOwnProperty("qrNum") &&
        routerQuery.qrNum !== undefined
      ) {
        this.qrNum = routerQuery.qrNum;
        this.fetchDeviceInfo({
          qrNum: routerQuery.qrNum,
          orgId: this.userInfo.orgId,
        });
      }
      if(routerQuery.hasOwnProperty("deviceId") &&
        routerQuery.deviceId !== undefined){
          this.qrNum = routerQuery.deviceId
          this.fetchDeviceInfo({
            qrNum: routerQuery.deviceId,
            orgId: this.userInfo.orgId,
          });
        }
      if (
        routerQuery.hasOwnProperty("chargeType") &&
        routerQuery.chargeType !== undefined
      ) {
        this.chargeType = routerQuery.chargeType;
        if (routerQuery.chargeType == "card") {
          this.balanceOption = "2";
        }
      }
    }else{
      this.$toast('授权登陆')
    }
  },
  mounted() {},
  watch: {},
  methods: {
    //设备信息
    async fetchDeviceInfo(params) {
      let result = await queryByQrCode(params);
      if (result.respCode !== "000000") {
        this.$toast(result.respMsg);
      } else {
        console.log(result,'fetchDeviceInfo');
        let deviceInfo = result.respObject;
        this.deviceInfo = deviceInfo;
        this.fechDeviceActive({
          saleId: deviceInfo.device.activityId
        })
      }
    },
    async fechDeviceActive(params) {
      let result = await queryDeviceActive(params);
      if (result.respCode !== "000000") {
        this.$toast(result.respMsg);
      } else {
        let activeInfo = result.respObject;
        activeInfo.map((item) => {
          item.active = false;
        });
        this.optionList = activeInfo;
      }
    },
    selectBalance(e) {
      this.balanceOption = e;
      this.chargeType = e == "1" ? "wallet" : "card";
    },
    handleOutBlur(e) {
      console.log(e);
      this.ecardNum = e.target.value;
    },
    onTap(list, idx) {
      this.optionList.map((item, index) => {
        idx === index ? (item.active = true) : (item.active = false);
      });
      this.money = this.optionList[idx].chargeAmount;
      (this.nominalValue = this.optionList[idx].nominalValue),
        (this.coupon = this.optionList[idx].givingAmount);
    },
    async handlePay() {
      let device = this.deviceInfo;
      let params = {
        specialId: this.userInfo.specialId,
        openId: this.userInfo.openId,
        totalFee: this.money,
        deviceCode: device.device.deviceCode,
        deviceName: device.device.area,
        payType: this.chargeType,
        amount: this.nominalValue, //充值金额
        coupon: this.coupon, //赠送金额
        orgId: device.device.orgId,
        saleId: this.optionList[0].saleId,
      };
      

      if (this.balanceOption == "2") {
        if (this.ecardNum == "") {
          this.$toast("请输入离线卡或检查卡号！");
          return;
        }
        if (this.ecardNumComp == "") {
          this.$toast("请再次输入卡号!");
          return;
        }
        if(this.ecardNum !== this.ecardNumComp){
          this.$toast('两次输入卡号不一致，请检查！')
          return
        }
      }
      if (
        this.money == '' ||
        this.nominalValue == '' ||
        this.coupon == null
      ) {
        this.$toast("请选择充值金额");
        return 
      }
      if (this.chargeType == "card") {
        params.cardNo = this.ecardNum;
      }
      let result = await openPayment(params);
      if (result.respCode == "000000") {
        let data = result.respObject;
        if (typeof WeixinJSBridge == "undefined") {
          if (document.addEventListener) {
            document.addEventListener(
              "WeixinJSBridgeReady",
              this.onBridgeReady(data),
              false
            );
          } else if (document.attachEvent) {
            document.attachEvent("WeixinJSBridgeReady", this.onBridgeReady(data));
            document.attachEvent("onWeixinJSBridgeReady", this.onBridgeReady(data));
          }
        } else {
          this.onBridgeReady(data);
        }
      } else {
        this.$toast("参数错误：");
      }
    },
    onBridgeReady(json) {
      let that = this;
      WeixinJSBridge.invoke("getBrandWCPayRequest", json, function (res) {
        // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回 ok，但并不保证它绝对可靠。
        if (res.err_msg == "get_brand_wcpay_request:ok") {
          if (that.chargeType == "wallet") {
            // location.href = "../";
            that.$router.replace({
              path: "/user/balance-user/index",
            });
          } else if (that.chargeType == "card") {
            // alert("充值电卡支付成功，请根据设备语音提示继续操作...");
            that.$router.replace({
              path: "/user/balance-user/index",
            });
          }
        } else {
          this.$toast("支付失败，请联系客服...");
        }
      });
    },
  },
  components: {
    balanceCard,
    noticePanel,
  },
};
</script>

<style scoped lang="less">
.balance-wrapper {
  box-sizing: border-box;
  width: 100%;
  padding: 15px;
}
.balance-wrapper .van-cell {
  margin-top: 15px;
}
.choose-option .option-radio--group {
  display: flex;
  align-items: center;
  justify-content: flex-end;
}
.choose-option .option-radio--group .van-radio {
  margin-left: 15px;
}
.balance-wrapper .van-cell .van-cell__title {
  flex: 0;
  -webkit-flex: 0;
  flex-basis: auto;
}
.select-money--button {
  margin-top: 15px;
  margin-bottom: 40px;
}
.protocol .van-checkbox .van-checkbox__label {
  display: flex;
  justify-content: flex-start;
  align-items: center;
}
.protocol .van-checkbox .protocol-text {
  color: #409eff;
}

.top-up--options {
  width: 100%;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  flex-wrap: wrap;
}
.top-up--options .select-option {
  width: 31.33333%;
  padding: 18px 15px;
  margin-right: 2%;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  border-radius: 5px;
  border: 1px solid #409eff;
  box-sizing: border-box;
  margin-bottom: 10px;
  text-align: center;
}
.top-up--options .select-option .select-block .num {
  font-size: 18px;
  color: #000;
  font-weight: bold;
}
.top-up--options .select-option .select-block {
  font-size: 12px;
}
.top-up--options .select-option.active {
  background: #409eff;
  color: #fff;
}
.top-up--options .select-option.active .num,
.top-up--options .select-option.active .discounts {
  color: #fff;
}
.card-container {
  width: 100%;
  height: 135px;
  border-radius: 5px;
  background-image: url(http://cloud.henankejue.com/staticfile/images/kejuewx/ecard2.png);
  background-repeat: no-repeat;
  background-size: cover;
  display: flex;
  justify-content: flex-start;
  align-items: center;
}

.card-container .card-content {
  padding: 15px;
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: flex-start;
}

.card-container .card-content .balance {
  font-size: 18px;
  color: #fff;
  margin-bottom: 20px;
}
.card-container .card-content .balance span {
  display: inline-block;
}
.card-container .card-content .services-site {
  font-size: 14px;
  color: #fff;
}
</style>
